// pages/index/details/index.js
import Dialog from '../../../../miniprogram_npm/@vant/weapp/dialog/dialog';
import Toast from '../../../../miniprogram_npm/@vant/weapp/toast/toast';
import {
	clearAlertRefresh
} from '../../../../utils/hooks';
import {
	bindProps,
	formatDateString
} from '../../../../utils/util';

const $api = require('../../../../request/api').API;
const app = getApp();
Page({
	/**
	 * 页面的初始数据
	 */
	data: {
		flowEndDate: '',
		activeDate: '',
		id: '',
		// 住户id
		houseId: '',
		// 呼叫器id
		beeperId: '',
		// 设备id
		equipId: '',
		infraredId: '',
		//--------------------------------------------------------------
		wifiName: '',
		wifiPwd: '',
		linkName: '',
		phone: '',
		address: '',
		provinceName: '',
		cityName: '',
		areaName: '',
		streetName: '',
		villageName: '',
		callingName: '',
		callingStatus: 0,
		callingErrorStatus: 0,
		equipNickName: '',
		installArea: '',

		equipCode: '',
		money: 0,
		// 标签列表
		tagList: [{
			beeperTagId: '1',
			tagName: '帅气'
		}],
		createDate: '',
		//-----------------------------------------------------------------
		// 设置wifi弹框
		showWifiOverlay: false,
		// 设置新增标签弹框
		showTagOverlay: false,
		// 点击标签分类显示
		selectClassShow: false,
		selectClassName: '点击选择分类',
		selectClassId: '',
		tagClass: [],
		// 是否为主用户
		mainFlag: 0,
		//
		showUpdateData: false,
		showType: 1, //1代表昵称修改 2代表安装区域修改
		// tempData:"",//临时数据，用来保存临时输入的值
		// tempData2:"",//零时数据，用来保存零时输入的值

		alarmModelList: [{
				id: 1,
				name: '长时间逗留'
			},
			{
				id: 2,
				name: '入寝指定时间'
			}
		],

		// 预警
		showAlarm: false, // 显示预警内容修改弹框
		showAlaramMode: false, // 显示预警模式选择
		showAlarmTime: false, // 显示预警时间段选择
		alarmModeName: '', // 预警模式的内容
		alarmMode: '', // 预警模式
		alarmTime: '', // alarmMode为1表示逗留时间 为2表示入寝时间段
		allowLeaveTime: '', // 无人时间
		latestTime: '', // 未起时间
		tempAlarmData: {
			// 临时的预警数据，还没提交之前的
			alarmModeName: '',
			alarmMode: '',
			alarmTime: '',
			allowLeaveTime: '',
			latestTime: ''
		},
		showTime: false, //显示时间选择
		currentTime: '', // 当前时间
		timeTitle: '开始时间', //时间标题
		selectTimeType: 1 // 1表示alarmTime选择开始时间，2表示alarmTime选择结束时间,3表示latestTime选择时间
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad(options) {
		let id = options.beeperId;
		if (id != undefined) {
			this.setData({
				id: id
			});
		}
	},

	// 请求数据
	async getData() {
		const {
			id,
			address,
			alarmModelList
		} = this.data;
		let res = await $api.getBeeperH({
			id
		});
		res = res.data.data;
		const modifyData = {
			houseId: res.houseId,
			beeperId: res.beeperId,
			createDate: res.createDate,
			activeDate: res.activeDate,
			equipId: res.equipId,
			wifiName: res.wifiName,
			wifiPwd: res.wifiPwd,
			linkName: res.linkName,
			phone: res.phone,
			address: res.address == '待补充' ? '' : res.address,
			provinceName: res.provinceName,
			cityName: res.cityName,
			areaName: res.areaName,
			streetName: res.streetName,
			villageName: res.villageName,
			callingName: res.equipName,
			callingStatus: res.equipState,
			callingErrorStatus: res.errorState,
			money: res.balance,
			tagList: res.tags,
			mainFlag: res.mainFlag,
			equipNickName: res.equipNickName,
			installArea: res.installArea,
			equipCode: res.equipCode,
			alarmTime: res.alarmTime,
			alarmMode: res.alarmMode,
			latestTime: res.latestTime,
			allowLeaveTime: res.allowLeaveTime,
			existPerson: res.existPerson,
			flowEndDate: res.flowEndDate == null ? '' : res.flowEndDate
		};
		if (res.alarmMode) {
			const target = alarmModelList.find(item => item.id == res.alarmMode);
			modifyData.alarmModeName = target.name;
		}
		if (!address) modifyData.showWifiOverlay = true;
		this.setData(modifyData);
	},
	// 打开wifi设置弹框
	openSetWifi() {
		this.setData({
			showWifiOverlay: true,
			linkName: this.data.contact,
			phone: this.data.phone
		});
	},
	// 关闭wifi设置弹框
	closeSetWifi() {
		if (this.data.address == '') {
			// 不填信息退出，直接解绑并回到首页
			this.jiebang();
			setTimeout(() => {
				wx.switchTab({
					url: '/pages/equipment/index'
				});
			}, 500);
		} else {
			this.setData({
				showWifiOverlay: false
			});
		}
	},

	isAlarmChange(){
		Dialog.confirm({
      title: '提示',
      showCancelButton: true,
      cancelButtonText: '取消',
      confirmButtonText: '确定',
      closeOnClickOverlay: true,
      message: '是否测试报警？'
    })
      .then(() => {
				$api.testAlarm({
					equipId: this.data.equipId
				}).then(res => {
					if (res.data.status == 0) {
						Toast.success("操作成功")
					} else {
						Toast.fail("操作失败")
					}
				}).catch(()=>{
					Toast.fail("操作失败")
				})
      })
      .catch(() => {
        
      });
	},

	onSelectClass(event) {
		console.log(event.detail);
		this.setData({
			selectClassName: event.detail.name,
			selectClassId: event.detail.id
		});
	},
	// 设置wifi
	setWIFI() {
		let params = {
			houseId: this.data.houseId,
			linkName: this.data.linkName,
			phone: this.data.phone,
			address: this.data.address,
			beeperId: this.data.beeperId
		};
		if (params.linkName == '') {
			Toast.fail('联系人不能为空');
			return;
		}
		if (params.phone == '') {
			Toast.fail('联系电话不能为空');
			return;
		}
		if (params.address == '') {
			Toast.fail('门牌号不能为空');
			return;
		}
		$api
			.setHouseWifi(params)
			.then(res => {
				console.log('设置wifi回调', res);
				if (res.data.status == 0) {
					wx.showToast({
						title: '设置地址信息成功'
					});
					this.setData({
						showWifiOverlay: false
					});
					this.getData(this.data.id);
				}
			})
			.catch(err => {
				console.log(err);
			});
	},

	// 跳转用户列表
	toWarningRecord() {
		console.log('equipId', this.data.equipId);
		wx.navigateTo({
			url: '../warningRecord/index?id=' + this.data.equipId
		});
	},
	// 解绑设备
	jiebang() {
		Dialog.confirm({
			title: '提示',
			message: '确认解绑当前设备吗？'
		}).then(() => {
			let params = {
				id: this.data.equipId
			};
			$api
				.unbindBinding(params)
				.then(res => {
					console.log('解绑设备', res);
					if (res.data.status == 0) {
						wx.showToast({
							title: '解绑成功！'
						});
						setTimeout(() => {
							wx.switchTab({
								url: '/pages/equipment/index'
							});
						}, 1000);
					}
				})
				.catch(err => {
					console.log('解绑设备', err);
				});
		}).catch(() => {

		});
	},
	// 解除警报
	jieAlarm() {
		Dialog.confirm({
			title: '提示',
			showCancelButton: true,
			cancelButtonText: '误触发',
			confirmButtonText: '已处理',
			closeOnClickOverlay: true,
			message: '确定解除警报吗？'
		}).then(() => {
			this.handleAlarmLiftedProcess()
		}).catch(() => {
			this.handleFalseAlarmRelease()
		});
	},
	/**
	 * 解除警报 - 已处理
	 */
	handleAlarmLiftedProcess() {
		$api.equipAllClear({
			equipId: this.data.equipId,
			cancelReason: 2
		}).then(() => {
			wx.showToast({
				title: '解除成功！'
			});
			clearAlertRefresh(this.data.id, this);
		});
	},

	/**
	 * 解除警报 - 误触
	 */
	handleFalseAlarmRelease() {
		$api.equipAllClear({
			equipId: this.data.equipId,
			cancelReason: 1
		}).then(() => {
			wx.showToast({
				title: '解除成功！'
			});
			clearAlertRefresh(this.data.id, this);
		});
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady() {},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow() {
		this.getData(this.data.id);
	},
	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide() {},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload() {},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh() {},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom() {},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage() {},
	contactInput(e) {
		let value = e.detail.value;
		this.setData({
			linkName: value
		});
	},
	phoneInput(e) {
		let value = e.detail.value;
		this.setData({
			phone: value
		});
	},
	addressInput(e) {
		let value = e.detail.value;
		this.setData({
			address: value
		});
	},
	tagNameInput(e) {
		let value = e.detail.value;
		this.setData({
			addTagName: value
		});
	},

	// 打开修改弹框
	openUpdateData(e) {
		let type = e.currentTarget.dataset.type;
		let tempData = '';
		switch (type) {
			case 1:
				tempData = this.data.equipNickName;
				break;
			case 2:
				tempData = this.data.installArea;
				break;
			case 3:
				tempData = this.data.alarmTime;
		}
		this.setData({
			showUpdateData: true,
			showType: type,
			tempData
		});
	},
	// 关闭修改弹框
	closeUpdateData() {
		this.setData({
			showUpdateData: false
		});
	},
	// 输入绑定
	dataInput(e) {
		let value = e.detail.value;
		this.setData({
			tempData: value
		});
	},
	// 确定更新
	async UpdateData() {
		const {
			tempData,
			showType,
			equipId,
			id
		} = this.data;
		if (!tempData && showType == 1) {
			Toast('请输入昵称');
			return;
		} else if (!tempData && showType == 2) {
			Toast('请输入安装区域');
			return;
		}
		let params = {
			id: equipId,
			name: tempData,
			state: showType
		};
		await $api.UpdataName(params);

		this.setData({
			showUpdateData: false
		});
		this.getData(this.data.id);
		wx.showToast({
			title: '设置成功'
		});
	},
	// 删除
	delete(e) {
		const {
			prop,
			type
		} = e.target.dataset;
		if (!prop || type !== 'delete') return;
		const modifyData = {
			[prop]: ''
		};
		prop == 'tempAlarmData.alarmModeName' && (modifyData['tempAlarmData.alarmMode'] = '');
		this.setData(modifyData);
	},
	// 预警输入
	handleAlarmInput(e) {
		console.log('输入', e);
		const {
			prop
		} = e.currentTarget.dataset;
		this.setData({
			[prop]: e.detail.value
		});
	},
	// 时间改变，需要时刻监听，否则的话不能及时获取修改时间
	handleTimeChange(e) {
		this.setData({
			currentTime: e.detail
		});
	},
	// 显示时间弹框
	showTimePopup(e) {
		let {
			type
		} = e.currentTarget.dataset;
		let {
			alarmTime,
			alarmMode,
			latestTime
		} = this.data.tempAlarmData;
		// 如果模式是1且type不是3就直接返回,是3的话就代表是选择离床时间
		if (alarmMode == 1 && type != 3) return;
		this.setData({
			showTime: true,
			selectTimeType: type || 1,
			currentTime: (type == 3 && !latestTime) || !alarmTime ?
				formatDateString(new Date(), 'HH:mm') : type == 3 ?
				latestTime : alarmTime.split('-')[0]
		});
	},
	// 关闭时间弹框
	closeTimePopup() {
		// 直接关闭时间弹框选择的时间就没有作用了
		this.setData({
			showTime: false
		});
	},
	// 确认时间
	confirmTime({
		detail
	}) {
		const {
			selectTimeType,
			tempAlarmData: {
				alarmTime
			}
		} = this.data;
		const modifyData = {};
		if (selectTimeType == 1) {
			this.time = detail;
			modifyData.selectTimeType = 2;
			// modifyData.currentTime = alarmTime?alarmTime.split("-")[1]:formatDateString(new Date(),"HH:mm")
		} else if (selectTimeType == 2) {
			modifyData['tempAlarmData.alarmTime'] = this.time + '-' + detail;
			this.closeTimePopup();
		} else if (selectTimeType == 3) {
			modifyData['tempAlarmData.latestTime'] = detail;
			this.closeTimePopup();
		}

		// console.log(modifyData.currentTime)

		this.setData(modifyData);
		// console.log(this.data.currentTime,"确认时间")
	},
	// 显示预警弹框
	showAlarmPopup() {
		const {
			tempAlarmData
		} = this.data;
		bindProps(tempAlarmData, this.data);
		this.setData({
			tempAlarmData,
			showAlarm: true
		});
	},
	// 关闭预警弹框
	closeAlarmPopup() {
		this.setData({
			showAlarm: false
		});
	},
	// 提交预警内容
	async confirmAlarm() {
		const {
			tempAlarmData,
			id
		} = this.data;
		const {
			alarmMode,
			alarmTime,
			allowLeaveTime,
			latestTime
		} = tempAlarmData;
		if (!alarmMode) return Toast.fail('请选择预警模式');
		if (!alarmTime) return Toast.fail(`请${alarmMode == 2 ? '选择入寝时间段' : '填写逗留时间'}`);
		if (alarmMode == 2) {
			if (!allowLeaveTime) return Toast.fail('请填写无人时间');
			if (!latestTime) return Toast.fail('请选择未起时间');
		}
		await $api.setAlarmMode({
			...tempAlarmData,
			infraredId: id
		});
		Toast.success('设置成功');
		this.closeAlarmPopup();
		this.getData();
	},

	// 显示预警模式
	showAlarmModePopup() {
		this.setData({
			showAlaramMode: true
		});
	},
	// 确定预警模式
	confirmAlarmMode({
		detail: {
			value
		}
	}) {
		const {
			tempAlarmData
		} = this.data;
		tempAlarmData.alarmMode = value.id;
		tempAlarmData.alarmModeName = value.name;
		tempAlarmData.alarmTime = '';
		tempAlarmData.allowLeaveTime = '';
		tempAlarmData.latestTime = '';
		this.setData({
			tempAlarmData,
			showAlaramMode: false
		});
	},
	// 关闭预警模式
	closeAlarmModePopup() {
		this.setData({
			showAlaramMode: false
		});
	}
});